package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.UserResponseVo;
import com.atguigu.gulimall.auth.service.ThirdPartFeignService;
import com.atguigu.gulimall.auth.service.UserFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author yanjingren
 * @Date 2021/6/7
 * @Description com.atguigu.gulimall.auth.controller
 */
@Controller
public class LoginController {
    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMVC viewController 将请求和页面映射过来
     */


    @Resource
    private ThirdPartFeignService feignService;
    @Resource
    private UserFeignService userFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // 1.TODO 接口防刷，防止60秒内再次发送验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60 * 1000) {
                R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        // 2.验证码的再次校验。存入redis，key=phone，value=code
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        feignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * //TODO 重定向携带数据，利用session原理，将数据放在session中，
     * 只要跳转到下一个页面取出这个数据，session中的数据就会删掉
     * //TODO 分布式下 session 的问题
     * RedirectAttributes redirectAttributes 重定向携带数据
     * redirectAttributes.addFlashAttribute("errors", errors); 只能取一次
     * @param vo 数据传输对象
     * @param result 用于验证参数
     * @param redirectAttributes 数据重定向
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult bindingResult, RedirectAttributes attributes) {
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(k -> k.getField(), v -> v.getDefaultMessage()));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 真正注册
        // 1.校验验证码
        String code = userRegisterVo.getCode();
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
        if (StringUtils.isNotEmpty(redisCode)) {
            if (code.equalsIgnoreCase(redisCode.split("_")[0])) {
                // 验证码通过
                // 删除验证码，令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
                // 调用远程服务注册
                R result = userFeignService.register(userRegisterVo);
                if (result.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    // 失败
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg", result.getData(new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes attributes, HttpSession session) {
        // 远程登录
        R r = userFeignService.login(userLoginVo);
        if (r.getCode() == 0) {
            // 成功
            session.setAttribute(AuthServerConstant.LOGIN_USER, r.getData(new TypeReference<UserResponseVo>(){}));
            return "redirect:http://gulimall.com";
        } else {
            // 失败
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData(new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            return "login";
        }
        return "redirect:http://gulimall.com";
    }
}
